package org.yuanqiframework.yuanqi.boot.sys.utils;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.yuanqiframework.yuanqi.boot.config.BootProperty;

@Component
public class SysRsaUtils implements ApplicationContextAware {
    private static String PRIVATE_KEY;
    private static String PUBLIC_KEY;
    private static RSA RSA;


    public static String getPublicKey() {
        return PUBLIC_KEY;
    }

    public static String getPrivateKey() {
        return PRIVATE_KEY;
    }

    public static String encrypt(String data) {
        return RSA.encryptBase64(data, KeyType.PublicKey);
    }

    public static String decrypt(String data) {
        return RSA.decryptStr(data, KeyType.PrivateKey);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BootProperty bootProperty = applicationContext.getBean("yuanqiBootProperty",BootProperty.class);
        String defaultRsaPrivateKey = bootProperty.getDefaultRsaPrivateKey();
        String defaultRsaPublicKey = bootProperty.getDefaultRsaPublicKey();
        if (defaultRsaPrivateKey==null){
            defaultRsaPrivateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOCQr1tpO1WlRargcV3u1ejQYXxTMzQT+wMLWkhaoaBRZOxcSK7He6V7aHviyNH8T6zwlJwrp12tP9PjR85GZevplR8VeWTHTjVBdGBBxeWIYw7/F3DkYnh/kqMu5zH+NRNuZstTZnqmxwhkSg4XzgYj4ZpFZWilJ52kXPHw2jO1AgMBAAECgYA8rjwEOmpDGVa69s0LcdcxguVkv+KtJt0EFJQ/yuWzuWrJB6LIP7UkoTU5jK1xOHmbJKMzlAQ0pvUBX3/uuE0fsbjrSYWeXB447W/j6W/AVZIP/ghoB/hEUHMPpW3izBlc7oQ7zawvur+LDPmPO2Zc3zLqzH8cBbU2v/dE+2dfgQJBAPDk3W0QHT0ygp+UCHHKWv6wUGkV7ghTq7rSGJ8GKZDmFLVmPB5SYxyHNQAxPHvpZ5v6sCto3bbRFrfJa2BP2FUCQQDupbBl+SHQNgV4PvO3AfLNx6dwzhcsBhB79gqP6ipxJsrqE+Hh07MOzmSblZ0icLF5dq299h3kgSpYhLWFrc3hAkEAwuV33IhgD6YxFqjvGBlO+6ZsuEi819HSLAlVUDvtH0V3VbhMRYAEng0qLWioddxGLmVpaQWj9AhAqBt3G2oeLQJBAImsrIcnoooroBwutQru5NQySjaZrmSHWxsoZg+AV9vPNWC096sAJlx0VTYsqeokeT5JaRId2kDpAzTt2oq0KgECQQCG2Qqw7G9+H4e61213Aw4rhf7gv15CaLCt+kQTkZ3eqWN1O+TPt6qPc3oyckLq47HT7rQEz4imG6wp070mKPRn";
        }
        if (defaultRsaPublicKey==null){
            defaultRsaPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgkK9baTtVpUWq4HFd7tXo0GF8UzM0E/sDC1pIWqGgUWTsXEiux3ule2h74sjR/E+s8JScK6ddrT/T40fORmXr6ZUfFXlkx041QXRgQcXliGMO/xdw5GJ4f5KjLucx/jUTbmbLU2Z6pscIZEoOF84GI+GaRWVopSedpFzx8NoztQIDAQAB";
        }
        PRIVATE_KEY = defaultRsaPrivateKey;
        PUBLIC_KEY = defaultRsaPublicKey;
        RSA = new RSA(defaultRsaPrivateKey, defaultRsaPublicKey);
    }
}
